from django import forms
from django.core.validators import RegexValidator

from . import models
from ..BaseForm import FormMixin


class RegisterForm(FormMixin, forms.ModelForm):
    account = forms.CharField(min_length=4, max_length=20, error_messages={
        "required": "请输入账号~~",
        "min_length": "账号长度为4-20~~",
        "max_length": "账号长度为4-20~~",
    })
    password = forms.CharField(min_length=4, max_length=20, error_messages={
        "required": "请输入密码~~",
        "min_length": "密码长度为4-20~~",
        "max_length": "密码长度为4-20~~",
    })
    nickname = forms.CharField(required=False, min_length=2, max_length=20, error_messages={
        "min_length": "昵称长度为2-20~~",
        "max_length": "昵称长度为2-20~~",
    })
    mobile_validator = RegexValidator(r"^1[3-9]\d{9}$", "手机号码格式不正确~~")
    phone = forms.CharField(required=False, min_length=11, max_length=11, error_messages={
        "min_length": "号码长度为11~~",
        "max_length": "号码长度为11~~",
    }, validators=[mobile_validator, ])

    class Meta:
        model = models.UserInfo
        fields = ['account', 'password', 'nickname', 'phone']

    def clean_account(self):
        account = self.cleaned_data.get('account')
        instance = models.UserInfo.objects.filter(account=account)
        if instance.exists():
            raise forms.ValidationError(f"{account}已注册~")
        return account

    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        if phone:
            instance = models.UserInfo.objects.filter(phone=phone)
            if instance.exists():
                raise forms.ValidationError(f"{phone}已注册~")
        return phone

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.set_password(instance.password)
        instance.save()
        return instance
